var app = getApp()
import Dialog from '@vant/weapp/dialog/dialog'
Page({
    data: {
        order_nav: [{
                name: '全部订单'
            },
            {
                name: '待处理'
            },
            {
                name: '已完成'
            },
            {
                name: '退款订单'
            }
        ],
        page: 1,
        order: [],
        ac_index: 0,
        order_index: 0,
        acti_index: 0,
        sellers_id: 0,
        isLoading: false, // 是否还能上拉刷新
        isFinish: false, // 是否加载完成
        num: 1,
        resdata: {},
        resdata2: {},
        id: '',
        timestr: '',
        timer: null,
        showFee: false
    },
    onShow() {
        this.getcount()
        this.init()
    },
    judgeState(information) {
        if (information.is_set_cash == 0) {
            wx.showModal({
                title: '温馨提示',
                content: '您还未设置提现信息，请先设置',
                showCancel: false,
                confirmText: '立即前往',
                complete: res => {
                    if (res.cancel) {
                        wx.navigateBack()
                    }

                    if (res.confirm) {
                        this.toCash()
                    }
                }
            })
        }
    },
    onLoad(query) {
        app.getUrl(this)
        app.getSystem(this)
        console.log(query)
        const information = JSON.parse(query.information)
        console.log(information, 'information')
        this.judgeState(information)
        this.setData({
            id: query.id,
            store_info: wx.getStorageSync('store_info'),
            page: 1,
            order_index: query.index
        })
    },
    init() {
        // wx.showToast({
        //   title: '未到提现时间，提现时间为每个月5-10号',
        //   icon: 'none'
        // })
        // Dialog.alert({
        //   title: '温馨提示',
        //   message: '您还未设置提现信息，请先设置',
        //   theme: 'round-button',
        //   confirmButtonText: 1,
        //   showConfirmButton: true
        // }).then(() => {
        //   // on close
        // });
        wx.request({
            url: app.siteInfo.siteroot_web,
            cachetime: '0',
            method: 'GET',
            data: {
                c: 'agent',
                a: 'getAgentInfo',
                user_id: app.globalData.userId
            },
            success: resp => {
                const res = resp.data
                console.log('res--is_expire', res)
                if (res.code == 0) {
                    // 请求成功
                    // res.data.end_time = new Date(res.data.end_time * 1000).toLocaleDateString()
                    this.setData({
                        resdata: res.data
                    })
                    if (res.data.is_expire == 1) {
                        // 只是弱提醒，不会关闭页面
                        wx.showModal({
                            title: '温馨提示',
                            content: res.data.cash_tips,
                            confirmText: '我知道了',
                            showCancel: false,
                            complete: res => {
                                if (res.cancel) {}

                                if (res.confirm) {
                                    wx.navigateBack()
                                }
                            }
                        })
                    }
                } else {
                    // 请求失败
                    wx.showToast({
                        icon: 'none',
                        title: res.msg
                    })
                }
            }
        })
    },

    countdown(time) {
        // body...
        var nowTime = +new Date() //返回当前时间总的毫秒数
        // var ddl = +new Date(time); //返回用户输入的截止时间
        var ddl = time * 1000 //返回用户输入的截止时间
        var res = ddl - nowTime //剩余时间总的毫秒数
        res = res / 1000 //毫秒换算成秒
        if (res <= 1) {
            clearInterval(this.data.timer)
            return '已结束'
        }
        var d = parseInt(res / 60 / 60 / 24) //天
        d = d < 10 ? '' + d : d
        var h = parseInt((res / 60 / 60) % 24) //时
        h = h < 10 ? '0' + h : h
        var m = parseInt((res / 60) % 60) //分
        m = m < 10 ? '0' + m : m
        var s = parseInt(res % 60) //秒
        s = s < 10 ? '0' + s : s
        return d + '天' + h + '时' + m + '分' + s + '秒'
    },

    getcount() {
        wx.request({
            url: app.siteInfo.siteroot_web,
            cachetime: '0',
            method: 'GET',
            data: {
                c: 'integral',
                a: 'getUserCartNum',
                user_id: app.globalData.userId
            },
            success: resp => {
                const res = resp.data
                console.log('res--', res)
                if (res.code == 0) {
                    // 请求成功
                    this.setData({
                        resdata2: res.data
                    })
                } else {
                    // 请求失败
                    wx.showToast({
                        icon: 'none',
                        title: res.msg
                    })
                }
            }
        })
    },

    /**
     * @function 获取订单列表
     * @param {*} cb 请求成功的回调cb，因为之前封装没有promise
     */
    getOrderList(cb) {
        // this.init(this.data.id)
        app.util.request({
            url: 'order/list',
            cachetime: '0',
            data: {
                seller_id: this.data.store_info.seller_id,
                merchant_status: this.data.order_index, // 0.全部，1. 待处理；2已完成；3退款订单
                page: this.data.page
            },
            testapi: app.siteInfo.siteroot_admin,
            success: res => {
                if (this.data.order.length === 0) {
                    this.setData({
                        order: res.data.data.data
                    })
                } else {
                    this.setData({
                        order: [...this.data.order, ...res.data.data.data]
                    })
                }
                // 不只有1页，并且当前页码小于总页码，则表示还可以上拉加载
                if (res.data.data.last_page !== 1 && this.data.page < res.data.data.last_page) {
                    this.setData({
                        isLoading: false
                    })
                } else {
                    this.setData({
                        isFinish: true
                    })
                }

                cb && cb()
            }
        })
    },
    /**
     * @function 跳转到订单详情
     * @param {*} e
     */
    goOrderDetail(e) {
        wx.navigateTo({
            url: './orderDetail/index?id=' + e.currentTarget.dataset.id
        })
    },
    /**
     * @function 订单筛选
     * @param {*} t
     */

    show() {
        // console.log(this.data.num)
        const instance = this.selectComponent('.child1') // 拿到子组件实例，不推荐
        console.log(instance.data.val) // 获取子组件property和data，用法一致
    },
    confirm(ev) {
        // 通过子组件emit反向传值，省略了遍历获取实例
        // console.log(ev.detail)
        // console.log(ev.currentTarget.dataset.setkey)
        this.setData({
            [ev.currentTarget.dataset.setkey]: ev.detail.age
        })
        console.log('页面值与组件值保持同步', this.data.num)
    },
    addcar() {
        wx.request({
            url: app.siteInfo.siteroot_web + '?c=integral&a=addGoodsCart',
            cachetime: '0',
            method: 'POST',
            data: {
                c: 'integral',
                a: 'addGoodsCart',
                user_id: app.globalData.userId,
                goods_id: this.data.id,
                num: this.data.num
            },
            success: resp => {
                const res = resp.data
                console.log('res--', res)
                if (res.code == 0) {
                    // 请求成功
                    wx.showToast({
                        title: '添加成功！'
                    })
                    this.getcount()
                } else {
                    // 请求失败
                    wx.showToast({
                        icon: 'none',
                        title: res.msg
                    })
                }
            }
        })
    },
    fast() {
        wx.navigateTo({
            url: `/zh_jdgjb/pages/pointsMall/placeOrder/index?order_type=1&goods_num=${this.data.num}&relate_id=${this.data.id}`
        })
    },
    gocar() {
        wx.navigateTo({
            url: '/zh_jdgjb/pages/pointsMall/shopCart/index'
        })
    },
    toMyHotel() {
        wx.navigateTo({
            url: '/zh_jdgjb/pages/agents/myHotel/myHotel'
        })
    },
    toFeeDetails() {
        wx.navigateTo({
            url: '/zh_jdgjb/pages/agents/feeDetails/index'
        })
    },
    toCashRecord() {
        wx.navigateTo({
            url: '/zh_jdgjb/pages/agents/cashRecord/index'
        })
    },
    toMyArea() {
        wx.navigateTo({
            url: '/zh_jdgjb/pages/agents/myarea/index'
        })
    },
    tomySalesman() {
        wx.navigateTo({
            url: '/zh_jdgjb/pages/agents/mySalesman/mySalesman'
        })
    },

    /**
     *
     */
    showtoasts() {
        wx.showModal({
            title: '温馨提示',
            content: '今日已完结的订单收益（不包含今日入住但未退房离开的订单）',
            confirmText: '我知道了',
            showCancel: false,
            complete: res => {
                if (res.cancel) {}

                if (res.confirm) {}
            }
        })
    },

    /**
     * 去提现
     */
    getMoney() {
        // < 500
        // wx.showToast({
        //   title: '佣金目前为0哦，快去赚取佣金吧',
        //   icon: 'none'
        // })
        if (this.data.resdata.is_expire == 1) {
            wx.showModal({
                title: '温馨提示',
                content: this.data.resdata.cash_tips,
                confirmText: '我知道了',
                showCancel: false,
                complete: res => {
                    if (res.cancel) {}

                    if (res.confirm) {}
                }
            })
            return
        }
        if (this.data.resdata.is_cash == 0) {
            wx.showToast({
                title: this.data.resdata.cash_tips,
                icon: 'none'
            })
            return
        } else {
            this.setData({
                showFee: true
            })
        }
    },
    toCash() {
        wx.redirectTo({
            url: '/zh_jdgjb/pages/agents/cashSetting/index'
        })
    },
    onClose() {
        this.setData({
            showFee: false
        })
    },

    applyCash() {
        wx.request({
            url: app.siteInfo.siteroot_web,
            cachetime: '0',
            method: 'GET',
            data: {
                c: 'agent',
                a: 'applyWithdraw',
                user_id: app.globalData.userId
            },
            success: resp => {
                const res = resp.data
                console.log('res--', res)
                if (res.code == 0) {
                    // 请求成功
                    wx.showToast({
                        title: '提现申请提交成功！',
                        icon: 'none'
                    })
                    this.onClose()
                    this.init()
                } else {
                    // 请求失败
                    wx.showToast({
                        icon: 'none',
                        title: res.msg
                    })
                }
            }
        })
    },
    /**
     * @function 下拉刷新
     */
    onPullDownRefresh: function () {
        this.setData({
            page: 1,
            isLoading: false,
            isFinish: false,
            order: []
        })
        this.getOrderList(() => {
            wx.stopPullDownRefresh()
        })
    },

    /**
     * @function 上拉加载回调
     */
    onReachBottom() {
        console.log(this.data.isLoading, this.data.page)
        if (!this.data.isLoading) {
            this.setData({
                isLoading: true,
                page: this.data.page + 1
            })

            this.getOrderList()
        }
    }
})